package midway.madness;

import java.util.ArrayList;
import java.util.List;

import midway.madness.utils.ApplicationEx;
import midway.madness.utils.SplashScreen;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListView;

/**
 * @author Brad
 *
 */
public class MidwayMadnessActivity extends Activity {
	
	private SplashScreen splash;
	private List<CategoryObject> mainMenuList = new ArrayList<CategoryObject>();
	private Handler handler;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        splash = new SplashScreen(this);
        splash.showSplash();
        
        setContentView(R.layout.main_menu);
        
        handler = new Handler(){
			public void handleMessage(Message msg){
				switch(msg.what){
				case ApplicationEx.HANDLE_ERR:
					ApplicationEx appEx = (ApplicationEx) getApplication();
		    		AlertDialog alert = appEx.handleError(MidwayMadnessActivity.this, msg.getData().getString("errorMsg"));
		    		alert.setOnDismissListener(new OnDismissListener() {
						
						public void onDismiss(DialogInterface dialog) {
							MidwayMadnessActivity.this.finish();
						}
					});
		    		splash.removeSplash();
		    		alert.show();
					break;
				default:
					break;
				}
			}
		};
        
        new DownloadTask().execute();
    }
    
    private class DownloadTask extends AsyncTask<Void, Void, Void>{
    	
		@Override
		protected Void doInBackground(Void... params) {
			JSONObject arr;
	        try{
				arr = ((ApplicationEx) getApplication()).getJson("http://midwaymadness.com/api/get_category_index/?dev=1");
				if (!arr.getString("status").equals("ok")){
		    		Bundle data = new Bundle();
		    		data.putString("errorMsg", ((ApplicationEx) getApplication()).getMessage(arr.getString("status")));
		    		Message msg = new Message();
		    		msg.what = ApplicationEx.HANDLE_ERR;
		    		msg.setData(data);
		    		handler.sendMessage(msg);
		    	}else{
		    		JSONArray categories;
		    		try {
		    			categories = arr.getJSONArray("categories");
		    			for (int i = 0; i < categories.length(); i++){
		    				JSONObject obj = categories.getJSONObject(i);
		    				if (obj.getInt("parent") != 0){
		    					continue;
		    				}
		    				String name = obj.getString("title");
		    				String slug = obj.getString("slug");
		    				int id = obj.getInt("id");
		    				int parId = obj.getInt("parent");
		    				mainMenuList.add(new CategoryObject(id, parId, name, slug));
		    			}
		    		} catch (JSONException e) {
		    			AlertDialog dialog = ((ApplicationEx) getApplication()).handleError(MidwayMadnessActivity.this, "reader");
		    			dialog.setOnDismissListener(new OnDismissListener() {
		    				
		    				public void onDismiss(DialogInterface dialog) {
		    					splash.removeSplash();
		    					MidwayMadnessActivity.this.finish();
		    				}
		    			});
		    			dialog.show();
		    		}
		    	}
	        }catch (JSONException e){
	        	AlertDialog dialog = ((ApplicationEx) getApplication()).handleError(MidwayMadnessActivity.this, "reader");
				dialog.setOnDismissListener(new OnDismissListener() {
					
					public void onDismiss(DialogInterface dialog) {
						splash.removeSplash();
						MidwayMadnessActivity.this.finish();
					}
				});
				dialog.show();
	        }
			return null;
		}
		
		protected void onPostExecute(Void v){
		  if (null != mainMenuList){
			final ListView listView = (ListView) findViewById(R.id.main_list_view);
			listView.setAdapter(new CategoryListAdapter(MidwayMadnessActivity.this, android.R.layout.simple_list_item_1, mainMenuList));
			listView.setTextFilterEnabled(true);
			listView.setOnItemClickListener(new OnItemClickListener() {
			  
			  public void onItemClick(AdapterView<?> adapterView, View view, int pos,
				  long id) {
				CategoryObject obj = mainMenuList.get(pos);
				Intent intent = new Intent(MidwayMadnessActivity.this, CategoryActivity.class);
				intent.putExtra("catName", obj.getName());
				intent.putExtra("catSlug", obj.getSlug());
				intent.putExtra("catId", obj.getId());
				intent.putExtra("catParId", obj.getParentId());
				startActivity(intent);
			  }
			});
			splash.removeSplash();
		  }
		}
    	
    }
    
/*
    private class DownloadTask extends AsyncTask<Void, Void, Void>{

		@Override
		protected Void doInBackground(JSONObject... params) {
	    	JSONArray categories;
			try {
				categories = params[0].getJSONArray("categories");
				for (int i = 0; i < categories.length(); i++){
					JSONObject obj = categories.getJSONObject(i);
					if (obj.getInt("parent") != 0){
						continue;
					}
					String name = obj.getString("title");
					String slug = obj.getString("slug");
					int id = obj.getInt("id");
					int parId = obj.getInt("parent");
					mainMenuList.add(new CategoryObject(id, parId, name, slug));
				}
			} catch (JSONException e) {
				AlertDialog dialog = ((ApplicationEx) getApplication()).handleError("reader");
				dialog.setOnDismissListener(new OnDismissListener() {
					
					public void onDismiss(DialogInterface dialog) {
						splash.removeSplash();
						MidwayMadnessActivity.this.finish();
					}
				});
				dialog.show();
			}
			return null;
		}
		
		protected void onPostExecute(Void v){
		  if (null != mainMenuList){
			final ListView listView = (ListView) findViewById(R.id.main_list_view);
			listView.setAdapter(new CategoryListAdapter(MidwayMadnessActivity.this, android.R.layout.simple_list_item_1, mainMenuList));
			listView.setTextFilterEnabled(true);
			listView.setOnItemClickListener(new OnItemClickListener() {
			  
			  public void onItemClick(AdapterView<?> adapterView, View view, int pos,
				  long id) {
				CategoryObject obj = mainMenuList.get(pos);
				Intent intent = new Intent(MidwayMadnessActivity.this, CategoryActivity.class);
				intent.putExtra("catName", obj.getName());
				intent.putExtra("catSlug", obj.getSlug());
				intent.putExtra("catId", obj.getId());
				intent.putExtra("catParId", obj.getParentId());
				startActivity(intent);
			  }
			});
			splash.removeSplash();
		  }
		}
    	
    }
*/    
    public void doSearch(View view){
    	String searchText = ((EditText) findViewById(R.id.search_txt)).getText().toString().trim();
    	if (searchText.equals("")){
    		return;
    	}
    	Intent intent = new Intent(MidwayMadnessActivity.this, SearchActivity.class);
    	intent.putExtra("searchText", searchText);
    	startActivity(intent);
    }
    
}